{- |

Module      :  Examples.InnerBase
Copyright   :  (c) The University of Kansas 2011
License     :  BSD3

Maintainer  :  nicolas.frisby@gmail.com
Stability   :  experimental
Portability :  see LANGUAGE pragmas (... GHC)

Lambda lifting without yoko.

-}





module Examples.LL0 where

import qualified Examples.InnerBase as I

import qualified Data.Set as Set
import qualified Data.IntMap as IM

import Examples.LLBasics










lambdaLift :: Inner -> [Type] -> Prog
lambdaLift x e = Prog (reverse tlds) main where
  (main, tlds) = runMnd (ll x) (e, IM.empty, 0)

ll (I.Lam ty tm) = newTLD ty (fvs tm) $ local updE $ ll tm where
  updE (rho, rn) = (ty : rho, support `prepend` rn) where
    support =
      IM.fromDistinctAscList . flip zip [0..] . Set.toAscList . fvs $ tm
ll (I.Var i) = asks $ \(_, rn) -> Var $ lookupRN rn i

---------------------------------------- default
ll (I.App tm1 tm2) = App <$> ll tm1 <*> ll tm2
 











env0 = [TBool, TBool, TArrow TInt TInt, TInt]
ex0 = I.Lam TInt $ I.Lam TInt $ I.Var 4 `I.App` I.Var 1 `I.App` I.Var 0
ex1 = ex0 `I.App` I.Var 3
ex2 = (I.Lam (TArrow TInt TInt `TArrow` TArrow TInt TInt) $ I.Var 0) `I.App`
      (I.Lam (TArrow TInt TInt) $ I.Var 0)

-- *LL> lambdaLift ex1 env0
-- Prog [([TArrow TInt TInt],TInt,App (App (DVar 0) (Var 1)) (Var 0)),
--       ([TArrow TInt TInt,TInt],TInt,App (App (Var 2) (Var 1)) (Var 0))
--      ] (App (App (DVar 0) (Var 2)) (Var 3))
